import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Set;

public class ServerReader extends Thread {
    private Socket socket;

    public ServerReader(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (DataInputStream dis = new DataInputStream(socket.getInputStream())) {
            while (true) {
                int flag = dis.readInt();
                if (flag == 1) {
                    handleLogin(dis);
                } else {
                    handleMessage(dis);
                }
            }
        } catch (IOException e) {
            handleDisconnect();
        }
    }

    private void handleLogin(DataInputStream dis) throws IOException {
        String name = dis.readUTF();
        ServerChat.onLineSockets.put(socket, name);
        broadcastSystemMessage(name + "上线了");
    }

    private void handleMessage(DataInputStream dis) throws IOException {
        String newMsg = dis.readUTF();
        String sendName = ServerChat.onLineSockets.get(socket);
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
        String formattedMsg = String.format("[%s][%s]: %s", 
            sendName, time, newMsg);
        broadcastMessage(formattedMsg);
    }

    private void handleDisconnect() {
        try {
            String username = ServerChat.onLineSockets.remove(socket);
            if (username != null) {
                broadcastSystemMessage(username + "异常断开连接");
            }
            socket.close();
        } catch (IOException ex) {
            System.err.println("关闭连接时出错: " + ex.getMessage());
        }
    }

    private void broadcastMessage(String msg) {
        broadcast(msg, false);
    }

    private void broadcastSystemMessage(String msg) {
        broadcast("[系统通知] " + msg, true);
    }

    private void broadcast(String msg, boolean includeSelf) {
        Set<Socket> clients = ServerChat.onLineSockets.keySet();
        synchronized (ServerChat.onLineSockets) {
            for (Socket client : clients) {
                try {
                    if (includeSelf || client != socket) {
                        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
                        dos.writeUTF(msg);
                        dos.flush();
                    }
                } catch (IOException e) {
                    System.err.println("发送消息失败: " + e.getMessage());
                }
            }
        }
    }
}
